import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:smart_translator/app/utils/tips.dart';
import '../../../style/app_colors.dart';
import '../../../widgets/CommonWidgets.dart';
import 'package:dio/dio.dart' as dio;

class LanguageOpinionController extends GetxController {

  var allLanguage = true.obs;
  List<Map<String,dynamic>> recentLangs = [];
  List<Map<String,dynamic>> allLangs = [];
  RxMap<String,dynamic> languagesMap = RxMap();

  var searchMode = false.obs;
  RxList<dynamic> searchResult = RxList();

  final needFilter = Get.arguments; //音视频翻译需要过滤掉一些语种
  List<String>filterList=['vi-VN','zh-HK','ja-JP','ko-KR','id-ID','th-TH','pt-PT','tr-TR','ar-AE','es-ES','hi-IN','fr-FR','ms-MY','fil-PH','de-DE','it-IT','ru-RU','sv-SE','da-DK','no-NO','zh-CN','en-US'];

  String? selectedLanguageCode;
  @override
  void onInit() {
    super.onInit();

    selectedLanguageCode = Get.parameters['code'];


    initRecentLangs();
    initAllLanguage();
  }

  void initRecentLangs() {
    recentLangs.add({
      "code": "zh-CN",
      "desc": "中文（普通话，中国大陆）",
      "supportDetection": true
    });

   recentLangs.add({
      "code": "en-US",
      "desc": "英语（美国）",
      "supportDetection": true
    });

    recentLangs.add({
      "code": "ja-JP",
      "desc": "日语（日本）",
      "supportDetection": true
    });

    recentLangs.add({
      "code": "fr-FR",
      "desc": "法语（法国）",
      "supportDetection": true
    });

    recentLangs.add({
      "code": "de-DE",
      "desc": "德语（德国）",
      "supportDetection": true
    });




  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }

  void switchAllLan() {
    allLanguage.value = true;
  }

  void switchAllOfflineLan() {
    allLanguage.value = false;
  }

  // 去掉不包含语种的字母项
  bool shouldIncludeLetter(String key, List<Map> value){
    bool isInclude =false;
    for(var i=0;i<filterList.length;i++){
      if(isInclude ==false){
        isInclude =value.any((ele)=>ele['code']==filterList[i]);
      }
    }
   return isInclude;
  }
  // 对字母项进行过滤（仅包含腾讯已有的语种）
   shouldIncludeLang(String key, value){
     return value.where((Map item){
       return filterList.contains(item['code']);
     });
  }

  List<Widget> generateRecentLangs() {
    List<Widget> recentLansWidget = [];
    recentLangs.forEach((item) {
      recentLansWidget.add(
          InkWell(
            onTap: () {
              selectedLangue(item);
            },
            child: Container(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Row(
                    children: [
                      (selectedLanguageCode != null && selectedLanguageCode == item['code'])? Text(item['desc'],style: TextStyle(color: AppColors.app_base_theme_color),):
                                    Text(item['desc'])
                    ],
                  ),
                  SizedBox(height: 17.h,),
                  CommonWidgets.getMyDivider(),
                  SizedBox(height: 17.h,)
                ],
              ),
            ),
          )

      );

    });

    return recentLansWidget;

  }


  void initAllLanguage() async {
    Tips.showLoading();
    dio.Response resp = await dio.Dio().get(
      'https://newtranx-zhiyi.oss-cn-shenzhen.aliyuncs.com/languages_zh.json',
        options: Options(
          headers: { // 请求头
            'Accept': 'application/json',
          },
          receiveTimeout: Duration(seconds: 20),
          sendTimeout: Duration(seconds: 20)
        )
    );

    Tips.dismissLoading();
    if(needFilter!=null && needFilter['filter']==true){
      Map<String, dynamic> filteredMap = {};
      for(var entry in resp.data.entries){
          var letterItem = entry.value;
          var tempList=[];
          for(var i=0;i<letterItem.length;i++){
             bool isInclude = filterList.contains(letterItem[i]['code']);
              if(isInclude){
                tempList.add(letterItem[i]);
              }
          }
           if(!tempList.isEmpty){
             filteredMap[entry.key] =tempList;
           }
      }
     languagesMap.value = filteredMap;
    }else{
      languagesMap.value = resp.data;
    }
    print('languagesMap resp.data ===> ${languagesMap.value}');
  }


  void searchContent(String v) {
    if (v.trim() == '') {
      searchMode.value = false;
    } else {
      searchMode.value = true;

      languagesMap.value.keys.forEach((itemKey) {
         var items = languagesMap.value[itemKey];
         items.forEach((item) {
           if (item['desc'].contains(v)) {
             searchResult.value.add(item);

           }
         });
      });
    }

  }

  void selectedLangue(Map item) {
     print('selected languages ::: ${item}');
     Get.back(result: item);
  }
}
